﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Resources;

namespace Songhay.Silverlight.Mvvm
{
    /// <summary>
    /// Static helpers for <see cref="System.Windows.UIElement"/>.
    /// </summary>
    public static class UIElementUtility
    {
        /// <summary>
        /// Loads a <see cref="System.Windows.UIElement"/> type
        /// from a resource in the application package.
        /// </summary>
        /// <typeparam name="TUIElement">The type of the UI element.</typeparam>
        /// <param name="uri">The URI.</param>
        public static TUIElement LoadFromXaml<TUIElement>(Uri uri) where TUIElement : UIElement
        {
            StreamResourceInfo streamInfo = Application.GetResourceStream(uri);

            if((streamInfo == null) && (streamInfo.Stream == null)) return default(TUIElement);
            using(StreamReader reader = new StreamReader(streamInfo.Stream))
            {
                return XamlReader.Load(reader.ReadToEnd()) as TUIElement;
            }
        }

        /// <summary>
        /// Loads a <see cref="System.Windows.UIElement"/> type
        /// from a well-formed xaml <see cref="System.String"/>.
        /// </summary>
        /// <typeparam name="TUIElement">The type of the UI element.</typeparam>
        /// <param name="xamlString">The xaml string.</param>
        public static TUIElement LoadFromXaml<TUIElement>(string xamlString) where TUIElement : UIElement
        {
            return XamlReader.Load(xamlString) as TUIElement;
        }
    }
}
